import { requestURL } from './config'

let user_t = { user_type: 3 }
let o = {}
const shop = uni.getStorageSync('shop')
const user = uni.getStorageSync('userInfo')
if (shop) o.customer_id = shop.customer_id
if (user) o.user_id = user.id
user_t = Object.assign({}, user_t, o)
// #ifdef MP-WEIXIN
user_t.user_type = 1
// #endif
function getType(data, method) { // 获取请求方式
	let type = {}
	if (!method) {
		method = 'post'
		type = {
			method,
			data: {
				...user_t,
				...data
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
		}
	} else {
		method = 'get'
		type = {
			method,
			params: {
				...data
			}
		}
	}
	return type
}

function request(data, url, method) {
	return new Promise((resolve, reject) => {
		const APP_USER = uni.getStorageSync('userInfo')
		if (!user_t.customer_id) {
			if (data && data.customer_id) user_t.customer_id = data.customer_id
		}
		if (data && data.user_id) user_t.user_id = data.user_id
		if (APP_USER) user_t.user_id = APP_USER.id
		console.log(getType(data, method))
		
		uni.request({
			url: requestURL + url,
			...getType(data, method),
			success: res => {
				resolve(res.data)
			},
			fail: err => {
				uni.hideLoading()
				uni.showModal({
					title: '',
					content: '服务器连接失败，请检查您的网络',
					showCancel: false
				})
				reject('服务器连接失败，请检查您的网络')
			}
		})
	})
}

export default function(data, url, method) {
	return request(data, url, method)
}